package com.example.demo7;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private IntentFilter intentFilter;
    private BroadcastTest broadcastTest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        intentFilter=new IntentFilter();
        //指定接收的广播信息值,系统网络发生变化的值为android.net.conn.CONNECTIVITY_CHANGE
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        broadcastTest=new BroadcastTest();
        //注册广播,参数为广播接收器的实例和意图过滤器的实例
        registerReceiver(broadcastTest,intentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //注销广播
        unregisterReceiver(broadcastTest);
    }

    /**
     * 广播接收器
     */
    class BroadcastTest extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            //接收到广播时弹出通知
            Toast.makeText(context,"网络发生变化",Toast.LENGTH_SHORT).show();
            String TAG = "消息";
            Log.d(TAG, "onReceive: 网络发生变化");
        }
    }
}
